package com.cfweb.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;

public class FormUtil {
	
	/**
	 * get String of form
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String getFormString(List<InputPart> params) throws Exception{
		if(params == null) {
			return null;
		}
		InputPart inputPart = params.get(0);
		InputStream inputStream = inputPart.getBody(InputStream.class, null);
		byte[] bytes = IOUtils.toByteArray(inputStream);
		return new String(bytes, "utf-8");
	}
	
	/**
	 * get boolean form form
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static boolean getFormBoolean(List<InputPart> params) throws Exception{
		if(params == null) {
			return false;
		}
		InputPart inputPart = params.get(0);
		InputStream inputStream = inputPart.getBody(InputStream.class, null);
		byte[] bytes = IOUtils.toByteArray(inputStream);
		return new Boolean(new String(bytes));
	}
	
	/**
	 * get a list of String
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static List<String> getFormList(List<InputPart> params) throws Exception{
		if(params==null){
			return null;
		}
		List<String> list = new ArrayList<String>();
		for(InputPart part : params) {
			InputStream inputStream = part.getBody(InputStream.class, null);
			byte[] bytes = IOUtils.toByteArray(inputStream);
			list.add(new String(bytes, "utf-8"));
		}
		return list;
	}

	/**
	 * make <b>file</b> by input stream <b>ins</b>
	 * @param ins
	 * @param file
	 * @throws Exception
	 */
	public static void inputstreamtofile(InputStream ins, File file) throws Exception{
		OutputStream os = new FileOutputStream(file);
		try {
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.flush();
		} catch (Exception e) {
			throw e;
		} finally {
			os.close();
			ins.close();
		}
	}
}
